from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from . import models
from . import forms

def index(request):
    return render(request, 'Test/index.html')
    
def create(request):
    if request.method == 'POST':
        register_form = forms.RegisterForm(request.POST)
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            email = register_form.cleaned_data.get('email')
            new_user = models.testUser()
            new_user.name = username
            new_user.email = email
            new_user.save()

            try:
                user = models.testUser.objects.get(name=username)
            except :
                message = '注册失败！'                
            message = '注册成功！'
            return redirect('/index/')
        else:
            return render(request, 'Test/create.html', locals())
    register_form = forms.RegisterForm()
    return render(request, 'Test/create.html', locals())

def search(request):
    if request.method == 'POST':
        search_form = forms.SearchForm(request.POST)
        if search_form.is_valid():
            username = search_form.cleaned_data.get('username')
            user_info = models.testUser.objects.filter(name=username)
            user = user_info[0]
        else:
            return render(request, 'Test/search.html', locals())
    search_form = forms.SearchForm()
    return render(request, 'Test/search.html', locals())
